﻿Imports AugmentLib.Database
Imports System.Configuration.ConfigurationManager
Imports AugmentLib.InputOutput.Encryption
Imports AugmentLib.WebComponent
Imports Lsk.Data
Imports Lsk.Business
Imports FlickrNet

Partial Class ValuationEntry
    Inherits System.Web.UI.Page


    Protected Sub BtnSave_Click(sender As Object, e As System.EventArgs) Handles BtnSave.Click

        'Check if should update or save
        Dim LelongId As Guid
        Dim savemode As Boolean = False
        If (lblhidPropertyId.Text = "") Then 'safe mode, new auction
            savemode = True
            Dim lelongExist As Boolean
            lelongExist = CheckLelongTips(txtLelongTipCode.Text)
            If (lelongExist) Then
                lblMsgError.Text = "PropertyCode already existed in the database. Please update instead of create new one."
                divError.Visible = True
                udpMessage.Update()
                Exit Sub
            End If
        End If

        Dim objDB As New Database(AppSettings("datasource"), AppSettings("database"), AppSettings("username"), AppSettings("password"), AppSettings("timeout"), AppSettings("pooling"))
        Try
            objDB.OpenConnection()
            objDB.InitDbTrans()
            objDB.AddParameter("LelongTipCode", Data.SqlDbType.NVarChar, txtLelongTipCode.Text) 'lenght=10
            objDB.AddParameter("UnitNo", Data.SqlDbType.NVarChar, txtUnitNo.Text) '50
            objDB.AddParameter("Address", Data.SqlDbType.NVarChar, txtAddress.Text) '300
            objDB.AddParameter("Price", Data.SqlDbType.Decimal, txtPrice.Text)
            objDB.AddParameter("Type", Data.SqlDbType.NVarChar, ddlProperyType.SelectedItem.Text) '50
            objDB.AddParameter("LandArea", Data.SqlDbType.BigInt, txtLandArea.Text)
            objDB.AddParameter("Unit", Data.SqlDbType.NVarChar, ddlUnit.SelectedItem.Text) '50
            objDB.AddParameter("AuctionDate", Data.SqlDbType.Date, Date.ParseExact(txtAuctionDate.Text, "dd-MMM-yyyy", Nothing))
            objDB.AddParameter("AuctionTime", Data.SqlDbType.Time, txtAuctionTime.Text)
            objDB.AddParameter("AuctionVenue", Data.SqlDbType.NVarChar, txtAuctionVenue.Text)
            objDB.AddParameter("Bank", Data.SqlDbType.NVarChar, ddlBank.SelectedItem.Text)
            objDB.AddParameter("Auctioneer", Data.SqlDbType.NVarChar, txtAuctioneer.Text)
            objDB.AddParameter("Lawyer", Data.SqlDbType.NVarChar, txtLawyer.Text)
            objDB.AddParameter("Description", Data.SqlDbType.Text, txtDescription.Text)
            objDB.AddParameter("CreateWho", Data.SqlDbType.UniqueIdentifier, New Guid(lblhidStaffId.Text))
            objDB.AddParameter("UpdateWho", Data.SqlDbType.UniqueIdentifier, New Guid(lblhidStaffId.Text))

            If String.IsNullOrEmpty(lblhidSListerId.Text.ToString.Trim()) Then
                objDB.AddParameter("AgentID", Data.SqlDbType.UniqueIdentifier, DBNull.Value)
            Else
                objDB.AddParameter("AgentID", Data.SqlDbType.UniqueIdentifier, New Guid(lblhidSListerId.Text))
            End If

            If String.IsNullOrEmpty(txtReminder.Text.ToString.Trim()) Then
                objDB.AddParameter("RemindDate", Data.SqlDbType.Date, DBNull.Value)
            Else
                objDB.AddParameter("RemindDate", Data.SqlDbType.Date, Date.ParseExact(txtReminder.Text, "dd-MMM-yyyy", Nothing))
            End If
            objDB.AddParameter("AgentRemark", Data.SqlDbType.NVarChar, txtAgentRemark.Text)

            If (savemode) Then
                LelongId = Guid.NewGuid
                objDB.AddParameter("LelongId", Data.SqlDbType.UniqueIdentifier, LelongId)
                objDB.dbVariable.SQLString = "INSERT INTO AW_Lelong (LelongId, LelongTipCode,UnitNo,Address,Price,Type,LandArea,AuctionDate,AuctionTime,AuctionVenue,Bank,Auctioneer,Lawyer,Description,AgentID,RemindDate,AgentRemark,CreateWho, Unit) " &
                    "VALUES (@LelongId, @LelongTipCode,@UnitNo,@Address,@Price,@Type,@LandArea,@AuctionDate,@AuctionTime,@AuctionVenue,@Bank,@Auctioneer,@Lawyer,@Description,@AgentID,@RemindDate,@AgentRemark,@CreateWho, @Unit)"

            Else
                objDB.AddParameter("LelongId", Data.SqlDbType.UniqueIdentifier, New Guid(lblhidPropertyId.Text))
                objDB.dbVariable.SQLString = "UPDATE AW_Lelong SET UnitNo=@UnitNo,Address=@Address,Price=@Price,Type=@Type,LandArea=@LandArea,AuctionDate=@AuctionDate,AuctionTime=@AuctionTime,AuctionVenue=@AuctionVenue,Bank=@Bank,Auctioneer=@Auctioneer,Lawyer=@Lawyer,Description=@Description,AgentID=@AgentID,RemindDate=@RemindDate,AgentRemark=@AgentRemark,UpdateDate=getdate(),UpdateWho=@UpdateWho, Unit=@Unit " &
                    " WHERE LelongId=@LelongId"
            End If

            objDB.ExecuteQuery(False)
            objDB.DbTransCommit()
            objDB.CloseConnection()

            'Success, alert success. Clear Textbox
            If (savemode) Then
                lblMsgSuccessful.Text = txtLelongTipCode.Text + " added successfully."
                lblhidPropertyId.Text = LelongId.ToString
            Else
                lblMsgSuccessful.Text = txtLelongTipCode.Text + " updated successfully."
            End If

            divSuccessful.Visible = True
            udpMessage.Update()
            'ClearForm()

            upPropertyDetail.Update()
        Catch ex As Exception
            If objDB.dbVariable.objConn.State = Data.ConnectionState.Open Then
                objDB.DbTransRollback()
                objDB.CloseConnection()
            End If
            lblMsgError.Text = ex.Message
            divError.Visible = True
            udpMessage.Update()

        End Try
    End Sub

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Session("StaffId") Is Nothing Then
            Response.Redirect("Default.aspx")

        Else
            lblhidStaffId.Text = Session("StaffId").ToString
            lblhidStaffType.Text = Session("StaffType").ToString
        End If

        If (lblhidStaffType.Text = "4" Or lblhidStaffType.Text = "6") Then
            Response.Redirect("Dashboard.aspx")
        End If

        If Not Page.IsPostBack Then
            If Not Request.QueryString("id") Is Nothing Then ' Need to load existing auction property
                lblhidPropertyId.Text = Request.QueryString("id") 'SymmetricDecryptFromHex(Request.QueryString("id"), "augment")
                Dim recordExist As Integer = LoadAuction(lblhidPropertyId.Text)
                If recordExist = 0 Then
                    lblhidPropertyId.Text = "" 'This record basically not exist.
                End If
            End If
        End If

    End Sub

    Protected Function LoadAuction(AuctionID As String) As Integer

        'Return 1 if the AuctionID exist, 0 if the property never exist.
        Dim retval = 0

        Dim objDB As New Database(AppSettings("datasource"), AppSettings("database"), AppSettings("username"), AppSettings("password"), AppSettings("timeout"), AppSettings("pooling"))
        Dim TempDT As New Data.DataTable

        objDB.OpenConnection()

        objDB.dbVariable.SQLString = "SELECT LelongId,LelongTipCode,UnitNo,Address,Price,Type,LandArea,Unit,AuctionDate,AuctionTime,AuctionVenue" &
            ",Bank,Auctioneer,Lawyer,Description,AgentID,RemindDate,AgentRemark,CreateDate,CreateWho,UpdateDate,UpdateWho " &
            "from AW_Lelong where StatusDelete != 1 and LelongId = @LelongId"
        objDB.AddParameter("@LelongId", Data.SqlDbType.UniqueIdentifier, New Guid(AuctionID))
        objDB.FillData(TempDT, "AW_Lelong", Database.SQLCommandType.NormalString)
        objDB.CloseConnection()

        For Each ReadRow As Data.DataRow In TempDT.Rows

            lblhidCreateDate.Text = ReadRow.Item("CreateDate").ToString
            If IsDBNull(ReadRow.Item("CreateDate")) Then
                lblhidSCreateDate.Text = ""
            Else
                lblhidSCreateDate.Text = ReadRow.Item("CreateDate").ToString
            End If
            txtLelongTipCode.Text = ReadRow.Item("LelongTipCode").ToString
            txtUnitNo.Text = ReadRow.Item("UnitNo").ToString
            txtAddress.Text = ReadRow.Item("Address").ToString
            txtPrice.Text = ReadRow.Item("Price").ToString

            If (IsNothing(ddlProperyType.Items.FindByText(ReadRow.Item("Type").ToString)) = False) Then
                ddlProperyType.ClearSelection()
                ddlProperyType.Items.FindByText(ReadRow.Item("Type").ToString()).Selected = True
            End If

            txtLandArea.Text = ReadRow.Item("LandArea").ToString
            If (IsNothing(ddlUnit.Items.FindByText(ReadRow.Item("Unit").ToString)) = False) Then
                ddlUnit.ClearSelection()
                ddlUnit.Items.FindByText(ReadRow.Item("Unit").ToString()).Selected = True
            End If

            txtAuctionDate.Text = Format(ReadRow.Item("AuctionDate"), "dd-MMM-yyyy")
            txtAuctionTime.Text = ReadRow.Item("AuctionTime").ToString
            txtAuctionVenue.Text = ReadRow.Item("AuctionVenue").ToString

            If (IsNothing(ddlBank.Items.FindByText(ReadRow.Item("Bank").ToString)) = False) Then
                ddlBank.ClearSelection()
                ddlBank.Items.FindByText(ReadRow.Item("Bank").ToString()).Selected = True
            End If

            txtAuctioneer.Text = ReadRow.Item("Auctioneer").ToString
            txtLawyer.Text = ReadRow.Item("Lawyer").ToString
            txtDescription.Text = ReadRow.Item("Description").ToString

            If ReadRow.Item("AgentID").ToString <> String.Empty Then
                lblSLister.Text = getName(ReadRow.Item("AgentID").ToString)
            End If
            If (ReadRow.Item("RemindDate").Equals(DBNull.Value)) Then
                'txtReminder.Text = ""
            Else
                txtReminder.Text = Format(ReadRow.Item("RemindDate"), "dd-MMM-yyyy")
            End If

            txtAgentRemark.Text = ReadRow.Item("AgentRemark").ToString
            retval = 1
        Next
        Return retval
    End Function

    Private Sub GetrepLister()
        Dim TempDT As New Data.DataTable
        Dim objDB As New Database(AppSettings("datasource"), AppSettings("database"), AppSettings("username"), AppSettings("password"), AppSettings("timeout"), AppSettings("pooling"))
        objDB.OpenConnection()

        objDB.dbVariable.SQLString = "SELECT StaffId,Name FROM AW_Staff WHERE StatusDelete = 0 ORDER BY Name"
        objDB.FillData(TempDT, "AW_Staff", Database.SQLCommandType.NormalString)

        objDB.CloseConnection()

        repListerList.DataSource = TempDT
        repListerList.DataBind()

    End Sub

    Protected Sub btnSListerList_Click(sender As Object, e As ImageClickEventArgs) Handles btnSListerList.Click
        lblhidListerType.Text = "S"
        GetrepLister()
        mpeListerListEntry.Show()
    End Sub

    Protected Sub repListerList_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.RepeaterCommandEventArgs) Handles repListerList.ItemCommand
        If e.CommandName.ToUpper = "SELECTITEM" Then
            lblSLister.Text = CType(repListerList.Items(e.CommandArgument).FindControl("lbtrepListerListEdit"), LinkButton).Text
            txtSLister.Text = lblSLister.Text
            lblhidSListerId.Text = CType(repListerList.Items(e.CommandArgument).FindControl("lblRepListerListId"), Label).Text
        End If

        Page.ClientScript.RegisterStartupScript(Me.[GetType](), "anchor", "location.hash = '#Lister';", True)
    End Sub

    Private Sub ClearForm()
        lblhidCreateDate.Text = ""
        lblhidSCreateDate.Text = ""
        txtLelongTipCode.Text = ""
        txtUnitNo.Text = ""
        txtAddress.Text = ""
        txtPrice.Text = ""
        ddlProperyType.ClearSelection()
        txtLandArea.Text = ""
        ddlUnit.ClearSelection()
        txtAuctionDate.Text = ""
        txtAuctionTime.Text = ""
        txtAuctionVenue.Text = ""
        ddlBank.ClearSelection()
        txtAuctioneer.Text = ""
        txtLawyer.Text = ""
        txtDescription.Text = ""
        txtReminder.Text = ""
        txtAgentRemark.Text = ""
        lblhidPropertyId.Text = ""
    End Sub

    Private Function CheckLelongTips(ByVal LelongTip As String) As Boolean

        If Trim(LelongTip) = "" Then
            Return False
        End If

        Dim objDB As New Database(AppSettings("datasource"), AppSettings("database"), AppSettings("username"), AppSettings("password"), AppSettings("timeout"), AppSettings("pooling"))
        Dim TempDT As New Data.DataTable
        Try
            objDB.OpenConnection()
            objDB.AddParameter("LelongTipCode", Data.SqlDbType.NVarChar, txtLelongTipCode.Text)
            objDB.dbVariable.SQLString = "Select LelongId from aw_lelong where LelongTipCode = @LelongTipCode and StatusDelete != 1"
            objDB.ExecuteQuery(False)
            objDB.FillData(TempDT, "AW_Lelong", Database.SQLCommandType.NormalString)
            objDB.CloseConnection()
            For Each ReadRow As Data.DataRow In TempDT.Rows
                Dim lelongID = ReadRow.Item("LelongId").ToString
                Return True
            Next

        Catch ex As Exception

        End Try

        Return False
    End Function
    Private Function getName(ByVal StaffId As String) As String
        Dim StaffName As String = String.Empty
        Dim objDB As New Database(AppSettings("datasource"), AppSettings("database"), AppSettings("username"), AppSettings("password"), AppSettings("timeout"), AppSettings("pooling"))
        Dim TempDT As New Data.DataTable

        objDB.OpenConnection()

        'objDB.dbVariable.SQLString = "Select Name FROM AW_Staff WHERE StaffId = @StaffId AND StatusDelete = 0"
        objDB.dbVariable.SQLString = "Select Name FROM AW_Staff WHERE StaffId = @StaffId"
        objDB.AddParameter("StaffId", Data.SqlDbType.UniqueIdentifier, New Guid(StaffId))

        objDB.FillData(TempDT, "AW_Staff", Database.SQLCommandType.NormalString)

        objDB.CloseConnection()

        If TempDT.Rows.Count > 0 Then
            StaffName = TempDT.Rows(0).Item("Name").ToString
        End If

        Return StaffName
    End Function

    Protected Sub btnBack_Click(sender As Object, e As EventArgs) Handles btnBack.Click
        Response.Redirect("Auction.aspx")
    End Sub

    Protected Sub btnUploadPhoto_Click(sender As Object, e As EventArgs) Handles btnUploadPhoto.Click
        Dim url As String

        If String.IsNullOrEmpty(lblhidPropertyId.Text) Then
            lblMsgError.Text = "Please save the entry first!."
            divError.Visible = True
        Else
            url = "UploadPhoto.aspx?id=" + lblhidPropertyId.Text

            If Session("Back") Is Nothing Then
                'This is when the entry is directly from the New Auction Entry
                Session.Add("Back", "Auction.aspx")
            End If
            Response.Redirect(url)
            End If

    End Sub
End Class
